package com.example.viewmodelstudio.lifeclcycle_chronometer;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.SystemClock;
import android.widget.Chronometer;

import com.example.viewmodelstudio.R;

/**
 * LifeCycle应用
 * 1,使用Lifecycle解耦页面与组件
 * 2,使用LifecycleService解耦Service与组件
 * 3,使用ProcessLifecycleOwner监听应用程序声明周期
 *
 * LifeCycle的好处
 *  1,帮助开发者建立可感知生命周期的组件
 *  2,组件在其内部管理自己的生命周期，从而降低模块耦合度
 *  3,降低内存泄露发生的可能性
 *  4,Activity,Fragment,Service,Application均有LifeCycle的支持
 */
public class MainActivity extends AppCompatActivity {

    private Chronometer chronometer;
    private MyChronometer myChronometer;
    private long chronometerTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        chronometer = findViewById(R.id.chronometer);

        myChronometer = findViewById(R.id.myChronometer);
        getLifecycle().addObserver(myChronometer);
    }

    @Override
    protected void onResume() {
        super.onResume();
        chronometer.start();
        chronometer.setBase(SystemClock.elapsedRealtime() - chronometerTime);
    }

    @Override
    protected void onPause() {
        super.onPause();
        chronometerTime = SystemClock.elapsedRealtime() - chronometer.getBase();
        chronometer.stop();
    }

}